<?php

namespace App\Message;

use App\Ws;

class AdmNotice
{
    static public $server = null;
    public $fd = null;
    public $info = [];

    public function __construct($server, $fd, $info)
    {
        self::$server = $server;
        $this->fd = $fd;
        $this->info = $info;
    }

    // send operation msg to admin notice client of same site
    public function msgToAdmin($msg)
    {
        foreach (Ws::$table::get('admTable') as $adminFd) {
            self::$server->push($adminFd['fd'], json_encode($msg));
        }
    }

    // deal with msg from admin and sent to same client
    public function notice()
    {
        $msg = [
            'siteName' => $this->info['siteName'],
            'notice' => $this->info['msg'],
            'time' => time(),
            'timer' => $this->info['time'],
        ];

        foreach (Ws::$table::get('uidTable') as $user) {
            if ($this->info['siteName'] === $user['site']) {
                self::$server->push($user['fd'], json_encode(['type' => 'adm_notice', 'msg' => $msg]));
            }
        }

        $redisPool = Ws::$redisPool['notice'];
        $redis = $redisPool->get();
        $redis->setex('adm_notice_' . $this->info['siteName'], $this->info['time'] * 24 * 60 * 60, json_encode($msg));
        $redisPool->put($redis);

        $this->msgToAdmin(['type' => 'notice_success', 'msg' => 'send successfully']);

        unset($msg);
        unset($redisPool);
    }

    // get msg from redis and send to admin client
    public function getNotice()
    {
        $redisPool = Ws::$redisPool['notice'];
        $redis = $redisPool->get();
        $noticeAll = $redis->keys("adm_notice_*");
        $redisPool->put($redis);
        unset($redisPool);

        $list = [];
        foreach ($noticeAll as $item) {
            $msg = $redis->get($item);
            $list[] = $msg;
        }
        unset($noticeAll);

        $this->msgToAdmin(['type' => 'notice_get', 'msg' => $list]);
        unset($list);
    }

    // delete msg from redis
    public function delete()
    {
        $redisPool = Ws::$redisPool['notice'];
        $redis = $redisPool->get();
        $redis->del('adm_notice_' . $this->info['siteName']);
        $redisPool->put($redis);
        unset($redisPool);

        $this->msgToAdmin(['type' => 'notice_delete', 'msg' => "delete successfully"]);
    }

    public function ping()
    {
        //  print "ping \r\n";
    }
}
